package com.example.springbootdemo.controller;

import com.alibaba.fastjson.JSON;
import com.example.springbootdemo.config.JwtConfig;
import com.example.springbootdemo.interface1.LimitType;
import com.example.springbootdemo.interface1.Limiting;
import com.example.springbootdemo.vo.ResultVo;
import com.example.springbootdemo.vo.UserVo;
import com.example.springbootdemo.handler.UserHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;


@RestController
@CrossOrigin
@Slf4j
public class UserController {

    @Autowired
    private UserHandler userService;

    /**
     * 获取有用户的信息
     *
     * @param inputMap
     * @return
     */
    @Limiting(time = 50, count = 1,limitType = LimitType.DEFAULT)
    @RequestMapping("/getList")
    public ResultVo getList(@RequestBody Map<String, Object> inputMap) {
        log.info("getListPageSize start");
        log.info(JSON.toJSONString(inputMap));
        return userService.getList(inputMap);
    }


    /**
     * 用户第三方登录接口
     *
     * @param code code
     * @return Result
     */
    @RequestMapping("/thirdPartyLogins")
    public void thirdPartyLogins(String code, HttpServletResponse httpServletResponse) throws IOException {
        log.info(code);
        PrintWriter writer = httpServletResponse.getWriter();
        String token = userService.thirdPartyLogins(code, writer);
        String s = " <script>" +
                " window.opener.postMessage('%s','%s')" + System.lineSeparator() +
                " window.close()" +
                "</script>";
        String url = "http://localhost:802";
        String script = String.format(s, token, url);
        writer.println(script);
    }

    @RequestMapping("/validateToken")
    public ResultVo validateToken(@RequestBody String token) {
        if (JwtConfig.validateToken(token)) {
            return ResultVo.success("OK");
        } else {
            return ResultVo.error("fail");
        }
    }

    @RequestMapping("/generateToken")
    public ResultVo generateToken(@RequestBody String name) {
        return ResultVo.success(JwtConfig.generateToken(name));
    }

    @RequestMapping("/user/login")
    public ResultVo login(@RequestBody UserVo user) {
        log.info("login start");
        ResultVo login = userService.login(user);
        return login;
    }

    @RequestMapping("/user/info")
    public ResultVo info(@RequestBody Map<String, Object> inputMap) {
        System.out.println(inputMap);
        return ResultVo.success(userService.getInfo(inputMap));
    }

}
